import { rejects } from 'assert';
import http from 'http' ;

const host = process.env.HOST;
const port = process.env.PORT; 

const cdpRequestOptions = 
{
        host: host,
        port: port,
        path: "/json/version",
        method: "GET",
        headers: 
        {
            "Host": "localhost",
            "Accept": "application/json",
        }
};

export class browserManagerUtils
{
    static async getData()
    {
        return await new Promise((resolve,reject)=>
        {
            const req = http.request(cdpRequestOptions, res =>
            {
                let body = "" ;
                res.on("data", chunk => (body += chunk)) ;
                res.on("end",() => resolve(body)) ;
            }) ;
            req.on("error",reject) ;
            req.end() ;
        }) ;
    }

    static async parseData(data)
    {
        let parsed; 
        try
        {
            return parsed = JSON.parse(data) ;
        }
        catch(err) {throw new Error(`Failed to parse JSON: ${err.message}, body=${data}`);}
    }

    static async getCDPUrl()
    {
        const data = await this.getData() ;
        const parsedData = await this.parseData(data) ;

        const wsUrl = parsedData.webSocketDebuggerUrl ;
        if(!wsUrl) {throw new Error("No webSocketDebuggerUrl in Chrome response");}

        return wsUrl.replace("ws://localhost", `ws://${host}:${port}`);
    }
}

